import {
  IUIActionResult,
  IUILogicParams,
  UIActionProviderBase,
} from '@ibiz-template/runtime';
import { IAppDEUIAction } from '@ibiz/model-core';

/**
 * @description 打开odoo聊天弹窗
 * @export
 * @class OpenOdooChatProvider
 * @extends {UIActionProviderBase}
 */
export class OpenOdooChatProvider extends UIActionProviderBase {
  /**
   * @description 执行界面行为
   * @param {IAppDEUIAction} action
   * @param {IUILogicParams} args
   * @returns {*}  {Promise<IUIActionResult>}
   * @memberof OpenOdooChatProvider
   */
  async execAction(
    action: IAppDEUIAction,
    args: IUILogicParams,
  ): Promise<IUIActionResult> {
    const actionResult: IUIActionResult = {};
    if (!ibiz.odooChatUtil) return actionResult;
    const { context, params, data } = args;
    const { frontAppViewId, appDataEntityId, appId, id, navigateParams } =
      action;
    // 处理参数
    const { resultContext, resultParams } = await this.handleParams(
      action,
      context,
      data,
      params,
    );
    if (!frontAppViewId) {
      ibiz.message.error(`界面行为 [${id}] 未配置聊天视图`);
      return actionResult;
    }
    const entityModel = appDataEntityId
      ? await ibiz.hub.getAppDataEntity(appDataEntityId, appId)
      : undefined;
    const item = data[0];
    const viewModel = await ibiz.hub.getAppView(frontAppViewId);
    // 标识属性
    const keyFieldId = entityModel?.keyAppDEFieldId || 'srfkey';
    // 文本属性
    const textFieldId = entityModel?.majorAppDEFieldId || 'srfmajortext';
    // 图标属性
    const iconField = navigateParams?.find(nav => nav.key === 'icon')?.value;
    let icon = viewModel.sysImage;
    if (iconField && item[iconField])
      icon = {
        appId,
        imagePath: item[iconField],
      };
    ibiz.odooChatUtil.addChat({
      icon,
      isOpen: true,
      key: item[keyFieldId],
      params: resultParams,
      context: resultContext,
      appViewId: frontAppViewId,
      caption: item[textFieldId],
    });
    return actionResult;
  }
}
